module dungeon.inventory;

import std.string;

import derelict.opengl.gl;

import nade.vector;
import nade.region;
import nade.color;
import nade.primitive;
import nade.font;
import nade.hud;

import dungeon.item;
import dungeon.character;


class Inventory {
	struct Slot {
		Item		item = null;
		uint		count = 0;
	}


	this()
	{
	}

	int insert(Item item, uint count = 1)
	{
		assert(item !is null);

		foreach(k, ref slot; _slots)
		{
			if(slot.item is item)
			{
				slot.count += count;
				_weight += item.weight*count;
				_volume += item.volume*count;

				return k;
			}
			else if(slot.item is null)
			{
				slot.item = item;
				slot.count = count;
				_weight += item.weight*count;
				_volume += item.volume*count;

				return k;
			}
		}

		return -1;
	}
	void insert(uint index, Item item, uint count = 1)
	{
		Item prev = _slots[index].item;
		if(prev !is null)
		{
			_weight -= prev.weight;
			_volume -= prev.volume;
		}

		_slots[index].item = item;
		_slots[index].count = count;
		if(item !is null)
		{
			_weight += item.weight;
			_volume += item.volume;
		}
	}

	int weight() { return _weight; }
	int volume() { return _volume; }

	Slot[] slots() { return _slots; }

	protected {
		Slot[42]	_slots;
		int			_weight = 0;
		int			_volume = 0;
	}
}
/* 

class InventoryWindow : LabelledWindow {
	this(Character character)
	{
		super("Inventory");

		_character = character;

		for(int y = 0;  y < 7;  ++y)
			for(int x = 0;  x < 6;  ++x)
				show(new SlotFrame(character.inventory._slots.ptr + (x + (6 - y)*6)), Region2(x*32 + 4, y*32 + 24, (x + 1)*32 + 4, (y + 1)*32 + 24));
	}

	override void renderWindow(const Region2 area)
	{
		super.renderWindow(area);

		font.print(area.min.x + 4, area.min.y + 4, format("Weight: %-4d Volume: %d", _character.inventory.weight, _character.inventory.volume), 14);
	}

	override Vector2i sizeMin() { return Vector2i(200, 268); }
	override Vector2i sizeMax() { return sizeMin; }

	protected {
		Character		_character;
	}


	class SlotFrame : IFrame {
		this(Inventory.Slot* slot)
		{
			_slot = slot;
		}

		override void render(const Region2 area)
		{
			if(_slot.item !is null)
			{
				glPushMatrix();
				((area.min + area.max)*0.5).translate;
				_slot.item.sprite.render(Vector2(32, 32));
				glPopMatrix();

				font.print(area.min.x + 1, area.max.y - 13, format("%d", _slot.count), 14);
			}

			Color.GREY.render;
			renderRectangle(area.min.as!Vector2r, area.max.as!Vector2r);
		}

		override bool click(Vector2 position)
		{
			if(_slot.item !is null  &&  _slot.item.use(_character))
			{
				if(--_slot.count <= 0) _slot.item = null;
			}

			return true;
		}

		override Vector2i sizeMin() { return Vector2i(32, 32); }
		override Vector2i sizeMax() { return sizeMin; }

		protected {
			Inventory.Slot*		_slot;
		}
	}
}
 */